package com.situ.allaia.controller;

import com.situ.allaia.common.Global;
import com.situ.allaia.model.CartItem;
import com.situ.allaia.model.User;
import com.situ.allaia.service.CartService;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/cart")
public class CartController {
    private final CartService cartService;

    public CartController(CartService cartService) {
        this.cartService = cartService;
    }

    //添加到购物车
    @PostMapping(value = "/add", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String, Object> addToCart(CartItem ci, HttpSession session) {
        User user = Global.findUser(session);
        boolean success = false;
        //数据库中已存在的购物车项
        CartItem dbItem = cartService.findByUserIdAndGoodId(user.getId(), ci.getGood().getId());
        if (dbItem != null) {
            dbItem.setAmount(dbItem.getAmount() + ci.getAmount());
            success = cartService.update(dbItem);
        } else {
            ci.setUserId(user.getId());
            success = cartService.save(ci);
        }

        List<CartItem> cis = cartService.findByUserId(user.getId());
        System.out.println(cis.size());
        return Map.of("success", success, "cartItemCount", cis.size());
    }

    //修改购物车项，修改数量
    @PutMapping(value = "/update", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String, Object> update(CartItem ci) {
        boolean success = cartService.update(ci);
        return Map.of("success", success);
    }

    //跳转到购物车页
    @GetMapping("/list")
    public String list(HttpSession session, Map<String, Object> map) {
        User user = Global.findUser(session);
        List<CartItem> items = cartService.findByUserId(user.getId());
        map.put("items", items);
        return "cart";
    }

    //删除购物车项
    @DeleteMapping(value = "/delete", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String, Object> delete(Integer id, HttpSession session) {
        if (id == null) {
            User user = Global.findUser(session);
            boolean b = cartService.deleteByUserId(user.getId());
            return Map.of("success", b);
        } else {
            boolean b = cartService.deleteById(id);
            return Map.of("success", b);
        }
    }
}
